const express = require("express");
const app = express();

const jwt = require("jsonwebtoken");
const expressJWT = require("express-jwt");
const cors = require("cors");

app.use(cors());
app.use(express.json());
app.use(express.urlencoded());

let secretKey = "yjwbest";
app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: ["/", "/login",/\/login$/],
  })
);

app.post('/login',(req,res)=>{
    if(req.body.uname != 'admin' || req.body.pwd != '123456') {
        return res.send({msg:'用户名或者密码错误'})
    }

    let token = jwt.sign({uname:req.body.uname,pwd:req.body.pwd},
        secretKey, {expiresIn:'20s'})

    res.send({
        status:200,
        msg:'登录成功',
        token: token
    })
})

app.get('/api/user',(req,res)=>{
    console.log(req.user);
    res.send({name:'获取用户信息成功',msg: "express 生成token  并且携带token 发送请求",user:req.user })
})

app.get('/logout',(req,res)=>{
    res.send({
        msg:'退出成功',
        status:200
    })
})

app.use((err,req,res,next)=>{
    console.log(err);
    if(err.name='UnauthorizedError') {
        return res.send({
            msg:'token 无效获取 请重新登陆',
            status:401
        })
    }

    res.send({
        status:500,
        msg:'未知错误'
    })

    next()
})

app.listen(3000,()=>{
    console.log('3000 running')
})